package com.hzy.fivepalace.service.task;

import com.hzy.fivepalace.common.consts.RedisKeyConsts;
import com.hzy.fivepalace.common.type.OrderStatusEnums;
import com.hzy.fivepalace.db.dao.DtsGoodsMapper;
import com.hzy.fivepalace.db.dao.DtsOrderGoodsMapper;
import com.hzy.fivepalace.db.dao.ex.DtsCouponUserMapperEx;
import com.hzy.fivepalace.db.domain.*;
import com.hzy.fivepalace.db.service.DtsGoodsProductService;
import com.hzy.fivepalace.db.service.DtsOrderService;
import jodd.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * redis监听过期key实现
 */
@Configuration
public class RedisVerdueKeyListening extends KeyExpirationEventMessageListener {


    private static final Logger logger = LoggerFactory.getLogger(RedisVerdueKeyListening.class);

    @Autowired
    private DtsOrderService dtsOrderService;

    @Resource
    private DtsOrderGoodsMapper dtsOrderGoodsMapper;

    @Resource
    private DtsGoodsMapper dtsGoodsMapper;

    @Autowired
    private DtsGoodsProductService productService;

    @Resource
    private DtsCouponUserMapperEx couponUserMapperEx;

    private final RedisTemplate<String, String> redisTemplate;

    public RedisVerdueKeyListening(RedisMessageListenerContainer listenerContainer, RedisTemplate<String, String> redisTemplate) {
        super(listenerContainer);
        this.redisTemplate = redisTemplate;
    }


    /**
     * 处理订单支付超时
     *
     * @param message
     * @param bytes
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(org.springframework.data.redis.connection.Message message, byte[] bytes) {
        //过期的缓存key
        String expiredKey = message.toString();
        if (expiredKey.startsWith(RedisKeyConsts.ORDER_TIME_OUT_LISTENING_KEY)) {//截取前缀是否是订单的缓存
            // 获取订单编号
            String orderNo = expiredKey.split(RedisKeyConsts.ORDER_TIME_OUT_LISTENING_KEY)[1];
            if (StringUtil.isNotBlank(orderNo)) {
                DtsOrder order = dtsOrderService.selectAppOrderByOrderNo(orderNo);
                if (null != order && order.getOrderStatus().intValue() == OrderStatusEnums.TYPE0.getType()) {
                    logger.info("----------订单【{}】,支付超时处理开始----------", orderNo);

                    try {
                        //使用的优惠券id
                        Integer couponsId = order.getCouponsId();
                        DtsOrderWithBLOBs orderUpd = new DtsOrderWithBLOBs();
                        orderUpd.setId(order.getId());
                        orderUpd.setCouponsId(0);
                        orderUpd.setCouponPrice(new BigDecimal("0.00"));
                        //订单状态改完已取消
                        orderUpd.setOrderStatus((short) OrderStatusEnums.TYPE6.getType());
                        orderUpd.setActualPrice(new BigDecimal("0.00"));
                        //订单关闭时间为当前时间
                        orderUpd.setEndTime(LocalDateTime.now());
                        orderUpd.setUpdateTime(LocalDateTime.now());
                        orderUpd.setDeleted(true);
                        dtsOrderService.updateById(orderUpd);
                        if(!order.getIsByVip()){
                            //查询订单商品信息
                            DtsOrderGoodsExample orderGoodsExample = new DtsOrderGoodsExample();
                            orderGoodsExample.createCriteria().andOrderIdEqualTo(order.getId()).andDeletedEqualTo(false);
                            List<DtsOrderGoods> goodsList = dtsOrderGoodsMapper.selectByExample(orderGoodsExample);
                            goodsList.forEach(item -> {
                                //恢复货品库存
                                productService.addStock(item.getProductId(), item.getNumber().shortValue());
                            });
                            if (null != couponsId && couponsId.intValue() > 0) {//使用了优惠券就更改优惠券为未使用
                                couponUserMapperEx.setCouponsStatusIsNoUse(couponsId);
                            }
                        }


                    } catch (Exception e) {
                        //手动回滚数据
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    }
                    logger.info("----------订单【{}】,支付超时处理完成----------", orderNo);

                }
            }

        } else if (expiredKey.startsWith(RedisKeyConsts.AUTOMATIC_RECEIPT_GOODS_KEY)) {//截取前缀是否是自动收货的缓存
            // 获取订单编号
            String orderNo = expiredKey.split(RedisKeyConsts.AUTOMATIC_RECEIPT_GOODS_KEY)[1];
            if (StringUtil.isNotBlank(orderNo)) {
                DtsOrder order = dtsOrderService.selectAppOrderByOrderNo(orderNo);
                if (null != order && order.getOrderStatus().intValue() == OrderStatusEnums.TYPE2.getType()&&order.getFreightType().intValue()==0) {



                    boolean isAutoTask=true;

                    if(!order.getIsByVip()){
                        //查询订单商品信息
                        DtsOrderGoodsExample orderGoodsExample = new DtsOrderGoodsExample();
                        orderGoodsExample.createCriteria().andOrderIdEqualTo(order.getId()).andDeletedEqualTo(false);
                        List<DtsOrderGoods> goodsList = dtsOrderGoodsMapper.selectByExample(orderGoodsExample);
                        if(!CollectionUtils.isEmpty(goodsList)){
                            for(DtsOrderGoods item:goodsList){
                                if(isAutoTask){
                                    DtsGoods goods=dtsGoodsMapper.selectByPrimaryKey(item.getGoodsId());
                                    if(null!=goods&&null!=goods.getBrokerageType()&&goods.getBrokerageType().intValue()==0){
                                        isAutoTask=false;
                                    }
                                }
                            }
                        }
                    }

                    if(isAutoTask){
                        logger.info("----------订单【{}】,自动收货处理完成----------", orderNo);
                        DtsOrderWithBLOBs orderUpd = new DtsOrderWithBLOBs();
                        orderUpd.setId(order.getId());
                        orderUpd.setUpdateTime(LocalDateTime.now());
                        orderUpd.setConfirmTime(LocalDateTime.now());
                        //修改订单状态为待评价
                        orderUpd.setOrderStatus((short) OrderStatusEnums.TYPE3.getType());
                        dtsOrderService.updateById(orderUpd);
                        logger.info("----------订单【{}】,自动收货处理开始----------", orderNo);
                    }



                }
            }


        }

    }

}
